package com.cacho.s2b.lesson.engine;

import com.cacho.s2b.lesson.assertion.Assertion;
import com.cacho.s2b.lesson.grammar.GrammarParser;
import com.cacho.s2b.lesson.util.JsonUtil;
import com.cacho.s2b.lesson.vo.ApiStepInfo;
import com.cacho.s2b.lesson.vo.ApiTestInfo;
import io.restassured.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apiguardian.api.API;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 接口数据处理
 * @Author LingWei
 * @date 2023/12/31
 **/
@Slf4j
public class ApiExpressEngine {
    private final String OBJ_EXPRESS_START = "{{obj(";  // 对象开始的字符串
    private final String JSON_EXPRESS_START = "{{json(";  // json开始的字符串
    private final String EXPRESS_END = ")}}";  // 结束的字符串
    private boolean useQuote; // 是否需要引号弄成字符串
    private ApiTestInfo tester = null;

    public ApiExpressEngine() {
    }

    public ApiExpressEngine(ApiTestInfo tester) {
        this.tester = tester;
    }

    // 对外入口，根据来源数据选择对应的返回数据
    public Object translate(String source) {
        if (source == null) {
            return null;
        }
        source = source.trim(); // 去除首尾空格
        if (source.startsWith(OBJ_EXPRESS_START) && source.endsWith(EXPRESS_END)) {
            try {
                return translateAsObject(source);
            } catch (Exception e) {
                Assertion.fail("处理数据为对象类型失败-->" + source + "-->错误信息为：" + e.getMessage());
                return null;
            }
        } else {
            return translateAsString(source);
        }
    }

    // 返回String类型
    private String translateAsString(String source) {
        // {{json({"id":"id1"})}}
        if (source.startsWith(JSON_EXPRESS_START) && source.endsWith(EXPRESS_END)) {
            useQuote = false;
            return source.substring(JSON_EXPRESS_START.length(), source.length() - EXPRESS_END.length());
        } else if (source.startsWith("[" + JSON_EXPRESS_START) && source.endsWith(EXPRESS_END + "]")) {
            useQuote = false;
            return "[" + source.substring(JSON_EXPRESS_START.length() + 1,
                    source.length() - EXPRESS_END.length() - 1) + "]";
        }
        useQuote = true;
        String temp = source;
        temp = replaceRegGrammar(temp);
        temp = temp == null ? "" : temp;
        return temp;
    }

    // 正则表达式获取实际需要的值
    private String replaceRegGrammar(String source) {
        String temp = source;
        final String REGEX = "\\{\\{([^{}]*)}}";  // {{#.response.body.msg}}
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(source);
        if (m.find()) {
            // 将{{}} 加回
            String realValue = regGrammar(String.format("{{%s}}", m.group(1)));
            log.info("转换前：{},转换后的数据：{}", source, realValue);
            if (source.equals(realValue)) {
                return source;
            }
            if (realValue == null) {
                return source;
            } else {
                temp = replaceFirstValue(temp, REGEX, realValue);
            }
            // 重复处理多个{{}}在一个参数内
            temp = replaceRegGrammar(temp);
        }
        return temp;
    }
    // 将{{}}替换为真实的value
    private String replaceFirstValue(String source, String regex, String realValue) {
        if (realValue == null) {
            return null;
        }
        return StringEscapeUtils.unescapeJava(source.replaceFirst(regex,realValue));
    }

    private String regGrammar(String val) {
        GrammarParser parser = new GrammarParser(val, this.tester);
        parser.parse();
        return parser.getResult();
    }

    private Object translateAsObject(String source) {
        return source;
    }

    public boolean isUseQuote() {
        return useQuote;
    }
}
